import zhilian
import pandas as pd
import re
from flask import Flask, request, render_template
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.charts import Bar
from pyecharts.charts import Map
from pyecharts.charts import Line

# 关于 CurrentConfig，可参考 [基本使用-全局变量]
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

app = Flask(__name__, static_folder="./static", template_folder="./templates")


def chooice(area):
    """area：北京、上海、广州、深圳、杭州、武汉"""
    df = pd.read_csv(f"{area}招聘信息.csv")
    return df


def print_table(df):
    # 详细数据
    table = df.head(20).to_html(index=False, justify="center", classes="my_tables")
    return table


def company_area(df, city):
    # 地区分析
    df_area = df[df["地点"].str.contains("-")]
    x_data = [
        i.split("-")[1] + "区"
        for i in df_area["地点"].value_counts().index.tolist()
        if "-" in i
    ]
    y_data = df_area["地点"].value_counts().values.tolist()
    map = (
        Map()
        .add("岗位数量", [list(z) for z in zip(x_data, y_data)], city)
        .set_global_opts(
            title_opts=opts.TitleOpts(title=f"{city}岗位数量分布"),
            visualmap_opts=opts.VisualMapOpts(
                max_=df_area["地点"].value_counts().max(),
                min_=df_area["地点"].value_counts().min(),
                range_color=["#43c6ac", "#f8ffae"],
            ),
            legend_opts=opts.LegendOpts(is_show=True),
        )
    )
    return map


def company_pie(df):
    # 公司分析
    x_data = df["公司规模"].value_counts().index.tolist()
    y_data = df["公司规模"].value_counts().values.tolist()
    pie = (
        Pie()
        .add("", [list(z) for z in zip(x_data, y_data)])
        .set_global_opts(
            title_opts=opts.TitleOpts(title="公司规模"),
            legend_opts=opts.LegendOpts(pos_left="15%"),
        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
    )
    return pie


def degree(df):
    # 学历分析
    bar = Bar()
    bar.add_xaxis(df["学历要求"].value_counts().index.tolist())
    bar.add_yaxis("学历分布", df["学历要求"].value_counts().values.tolist())
    bar.set_global_opts(title_opts=opts.TitleOpts(title="学历分析"))
    return bar


def salary(df):
    # 薪资分析
    df_area = df[df["地点"].str.contains("-")]
    df_salary = df_area.query('薪资范围 != "薪资面议" and 薪资范围 != "面议" ')
    df_salary = df_area[~df_area["薪资范围"].str.contains(re.compile(r"天|月|次|以下"))]

    df_salary["薪资下限"] = df_salary["薪资范围"].str.split("-").str[0]
    df_salary["薪资上限"] = df_salary["薪资范围"].str.split("-").str[-1]

    df_salary["薪资下限"] = df_salary["薪资下限"].apply(
        lambda x: float(x.replace("万", "")) * 10000
        if "万" in x
        else float(x.replace(r"千", "")) * 1000
        if "千" in x
        else x
    )

    df_salary["薪资上限"] = df_salary["薪资上限"].apply(
        lambda x: float(x.replace("万", "")) * 10000
        if "万" in x
        else float(x.replace(r"千", "")) * 1000
        if "千" in x
        else x
    )

    df_salary["薪资范围"] = (df_salary["薪资上限"] + df_salary["薪资下限"]) / 2

    return df_salary


def area_salary(df_salary):
    # 地区
    area_salary = (
        df_salary.groupby("地点").agg({"薪资范围": "mean"}).reset_index().sort_values("薪资范围")
    )
    x_data = [i.split("-")[1] for i in area_salary["地点"].to_list()]
    y_data = [round(i, 2) for i in area_salary["薪资范围"].to_list()]

    line = (
        Line(init_opts=opts.InitOpts(width=1500))
        .add_xaxis(x_data)
        .add_yaxis("平均薪资", y_data)
        .set_global_opts(title_opts=opts.TitleOpts(title="各地区薪资情况"))
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True, position="top"))
    )
    return line


def degree_salary(df_salary):
    # 学历
    degree_salary = (
        df_salary.groupby("学历要求")
        .agg({"薪资范围": "mean"})
        .reset_index()
        .sort_values("薪资范围")
    )
    x_data = degree_salary["学历要求"].tolist()
    y_data = [round(i) for i in degree_salary["薪资范围"].to_list()]

    bar = (
        Bar(init_opts=opts.InitOpts(width=1500))
        .add_xaxis(x_data)
        .add_yaxis("平均薪资", y_data)
        .set_global_opts(title_opts=opts.TitleOpts(title="各学历薪资情况"))
        .set_series_opts(label_opts=opts.LabelOpts(is_show=True, position="top"))
    )
    return bar


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/result", methods=["POST"])
def result():
    keys = request.form["keys"]
    area = request.form["area"]
    zhilian.main(area, keys)
    df = chooice(area)
    df_salary = salary(df)
    table = print_table(df)
    company_area(df, area)
    companyPie = company_pie(df)
    degreeBar = degree(df)
    salaryLine = area_salary(df_salary)
    salaryBar = degree_salary(df_salary)
    return render_template(
        "simple_chart.html",
        area=area,
        keys=keys,
        table=table,
        # area_data = areaMap.dump_options(),
        company_data=companyPie.dump_options(),
        degree_data=degreeBar.dump_options(),
        salary_area_data=salaryLine.dump_options(),
        salary_degree_data=salaryBar.dump_options(),
    )


if __name__ == "__main__":
    app.run()
